package com.xj.controller;

import com.xj.pojo.User;
import com.xj.service.UserService;
import com.xj.util.JwtHelper;
import com.xj.util.Result;
import com.xj.util.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 努力的派大星
 * @version 1.0
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpServletRequest request){
        try {
            User loginUser = userService.login(user);
            Map<String, Object> map = new HashMap<>();
            if (loginUser != null) {
                String token = JwtHelper.createToken(loginUser.getId().longValue());
                map.put("token", token);
                return Result.ok(map);
            } else {
                throw new RuntimeException("用户名或密码错误");
            }
        } catch (RuntimeException e) {
            return Result.fail().message("用户名或密码错误");
        }
    }
    @GetMapping("/getInfo")
    public Result getInfo(@RequestHeader String token){
        boolean expiration = JwtHelper.isExpiration(token);//验证token是否过期
        if (expiration) {
            Result.build(null, ResultCodeEnum.CODE_ERROR);
        }
        Long userId = JwtHelper.getUserId(token);
        Map<String, Object> map = new HashMap<>();
        User user = userService.getUserById(userId);
        map.put("user", user);
        return Result.ok(user);
    }
    @GetMapping("/loginVerify")
    public Result test(String username){
        User user = userService.getUserByUsername(username);
        if(user != null){
            return Result.ok().message("√");
        }else {
            return Result.fail().message("用户不存在");
        }
    }
}
